class WordProcessing:
    # 用于将以换行分割的txt文件中的关键词转换为list
    def txt_to_list_keyword(self, stop_keyword_file_path, encoding='ANSI'):
        key_content = self.open_txt(stop_keyword_file_path, encoding=encoding)
        key_content = key_content.replace(' ', '')
        key_list = key_content.split("\n")
        key_list = set(key_list)

        return list(key_list)

    # 用于调整词云配色传入color_func
    def color_func(self, color_mod=None):
        import random
        def random_color_func1(word=None, font_size=None, position=None, orientation=None, font_path=None,
                               random_state=None):
            r = random.randint(70, 200)
            g = random.randint(0, 0)
            b = random.randint(170, 200)
            return 'rgb({:.0f}, {:.0f}, {:.0f})'.format(r, g, b)

        def random_color_func2(word=None, font_size=None, position=None, orientation=None, font_path=None,
                               random_state=None):
            r = random.randint(50, 100)
            g = random.randint(80, 160)
            b = random.randint(100, 200)
            return 'rgb({:.0f}, {:.0f}, {:.0f})'.format(r, g, b)

        def random_color_func3(word=None, font_size=None, position=None, orientation=None, font_path=None,
                               random_state=None):
            if font_size <= 20 and font_size != None:
                g = random.randint(120, 200)
                b = random.randint(150, 250)
                r = 470 - g - b
            else:
                g = random.randint(80, 160)
                b = random.randint(100, 200)
                r = 360 - g - b
            return 'rgb({:.0f}, {:.0f}, {:.0f})'.format(r, g, b)

        if color_mod == 1:
            return random_color_func1
        if color_mod == 2:
            return random_color_func2
        if color_mod == 3:
            return random_color_func3
        if color_mod is None:
            return None

    # 用于制作词云，传入以空格分割的str，自动统计词频
    def wordcloud(self, font_path, content, image_path, save_name='wordcloud.png', max_words=200, width=400,
                  height=200, random_state=1,
                  max_font_size=None, min_font_size=4, relative_scaling=0.5, prefer_horizontal=0.9, color_mod=1):
        from wordcloud import WordCloud
        import matplotlib.pyplot as plt

        backgroud_Image = plt.imread(image_path)
        wordcloud = WordCloud(
            background_color='white',  # 设置背景颜色
            collocations=False,  # 是否包括两个词的搭配,默认true，但词少的时候会重复
            font_path=font_path,  # 若是有中文的话，这句代码必须添加，不然会出现方框，不出现汉字
            mask=backgroud_Image,  # 设置背景图片
            max_words=max_words,  # 设置最大现实的字数
            width=width, height=height,  # 设置高和款
            prefer_horizontal=prefer_horizontal,  # 词语水平方向排版出现的频率
            max_font_size=max_font_size, min_font_size=min_font_size,  # 设置字体最大值
            relative_scaling=relative_scaling,  # 词频和字体大小的关联性
            random_state=random_state,  # 设置有多少种随机生成状态，即有多少种配色方案
            color_func=self.color_func(color_mod=color_mod)
        ).generate(content)

        # 显示生成的词云
        plt.imshow(wordcloud)
        plt.axis("off")
        plt.show()
        wordcloud.to_file(save_name)  # 保存图片

    # 制作反映主要问题的词频统计表、词云图并保存
    def wordcloud_rank(self, data, drop_top=None, data_column='反映问题A', excel_name='咨询反映主要问题.xls',
                       jpg_name='反映主要问题.png',
                       max_font_size=80, min_font_size=6, random_state=60, color_mod=1):

        problem_rank = data[data_column].value_counts().to_frame().reset_index()
        problem_rank.columns = ['关键词', '词频']
        problem_rank.to_excel(self.floder_output + '排名_' + excel_name, index=False)

        # 从排名表中删除频次最高的几个不放入云中
        problem_rank_cut = problem_rank
        if drop_top != None:
            drop_index = [i for i in range(drop_top)]
            problem_rank_cut = problem_rank.drop(drop_index, axis=0)  # 删除top数据
            problem_rank_cut.reset_index(drop=True, inplace=True)  # dorp_top后索引会变，所以要重设索引

        # 将problem_rank按词频转换成可用于制作词云的str（以空格分割）
        problem_rank_str = ''
        for line in range(problem_rank_cut.shape[0]):
            str = (problem_rank_cut['关键词'][line] + ' ') * int(problem_rank_cut['词频'][line]) + ' '
            problem_rank_str = problem_rank_str + str
        problem_rank_str = problem_rank_str.replace('、', '')

        # 进行词云的制作
        font_path = 'C:/Windows/Fonts/simhei.ttf'
        image_path = '词云背板\\椭圆.jpg'
        content = problem_rank_str
        save_name = self.floder_output + '词云_' + jpg_name
        width = 800
        height = 400
        max_font_size = max_font_size
        min_font_size = min_font_size
        random_state = random_state
        prefer_horizontal = 1  # 全部横着
        self.wordcloud(font_path, content, image_path, save_name=save_name, prefer_horizontal=prefer_horizontal,
                       max_font_size=max_font_size, min_font_size=min_font_size,
                       width=width, height=height, random_state=random_state, color_mod=color_mod)

        return problem_rank


#制作词云，输入需要为一整个str，词之间以空格相连
def wordcloud(image_path,font_path,content,save_name='wordcloud.png',max_words=200):
    from wordcloud import WordCloud
    import matplotlib.pyplot as plt

    backgroud_Image = plt.imread(image_path)
    wordcloud = WordCloud(
        background_color='white',# 设置背景颜色
        mask=backgroud_Image,# 设置背景图片
        font_path=font_path,  # 若是有中文的话，这句代码必须添加，不然会出现方框，不出现汉字
        max_words=max_words, # 设置最大现实的字数
        max_font_size=150,# 设置字体最大值
        random_state=10# 设置有多少种随机生成状态，即有多少种配色方案
    ).generate(content)

    # 显示生成的词云
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file(save_name)#保存图片

#制作词云，输入需要为一整个str，词之间以空格相连
def wordcloud2(font_path,content,image_path,save_name='wordcloud.png',max_words=200,width = 400,height = 200,random_state = 1,
              max_font_size=None,min_font_size=4,relative_scaling=0.5,prefer_horizontal=0.9):
    from wordcloud import WordCloud
    import matplotlib.pyplot as plt

    backgroud_Image = plt.imread(image_path)
    wordcloud = WordCloud(
        background_color='white',# 设置背景颜色
        collocations=False,#是否包括两个词的搭配,默认true，但词少的时候会重复
        font_path=font_path,  # 若是有中文的话，这句代码必须添加，不然会出现方框，不出现汉字
        mask=backgroud_Image,  # 设置背景图片
        max_words=max_words, # 设置最大现实的字数
        width=width, height=height, # 设置高和款
        prefer_horizontal=prefer_horizontal, #词语水平方向排版出现的频率
        max_font_size=max_font_size,min_font_size=min_font_size,# 设置字体最大值
        relative_scaling = relative_scaling,#词频和字体大小的关联性
        random_state = random_state # 设置有多少种随机生成状态，即有多少种配色方案
    ).generate(content)

    # 显示生成的词云
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file(save_name)#保存图片
#生成自定义权重制作词云的内容
def wordcloud_content(path):
    content = open_txt(path,encoding='ANSI')#打开txt文件
    content = content.split('\n')#按回车把内容进行分割做成列表
    weight_dict = {0:160,1:80,2:80,3:50,4:50,5:50,6:30,7:30,8:30,9:30,10:20,
                   11:20,12:20,13:20,14:20,15:20,16:10,17:10,18:10,19:10,20:10,
                   21:10,22:10,23:10,24:10,25:10,26:10,27:10,28:10,29:10,30:10,31:10}
    count = 0
    cloud_list = []
    for i in content:
        word_list = []
        word_list.append(i)
        print(count)
        print(word_list)
        word_list = word_list * weight_dict[count]
        cloud_list = cloud_list + word_list
        count+=1
    from random import shuffle
    shuffle(cloud_list)#对list进行乱序，不乱序的话做的图会有问题
    cloud_content = " ".join(cloud_list)#将list合并成str，以空格分割
    print(cloud_content)
    return cloud_content

